package com.ccp.dev.workflow.listener;

import com.ccp.dev.workflow.bpmconst.BpmConst;
import com.ccp.dev.workflow.dao.BpmProStatusDao;
import com.ccp.dev.workflow.model.TaskOpinion;
import com.ccp.dev.workflow.model.bpm.ProcessCmd;
import com.ccp.dev.workflow.service.bpm.thread.TaskThreadService;
import org.flowable.bpmn.model.Activity;
import org.flowable.bpmn.model.MultiInstanceLoopCharacteristics;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.delegate.DelegateExecution;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassDescribe:
 * 外部子流程启动事件监听器。
 * <pre>
 * 	1.用于修改子流程节点的状态为正在结束。
 *  2.在子流程调用任务结束后，将人员变量删除。
 * </pre>
 * @author :wangcheng
 * Date: 2019-05-13
 */
@Component
@SuppressWarnings("serial")
public class CallSubProcessEndListener extends BaseNodeEventListener{
    @Resource
    private BpmProStatusDao bpmProStatusDao;

    @Override
    protected void execute(DelegateExecution execution, String procDefId, String nodeId) {
        String processInstanceId = execution.getProcessInstanceId();
        String varName = execution.getCurrentActivityId() + "_" + BpmConst.SUBPRO_EXT_MULTI_USERIDS;
        ProcessCmd processCmd = TaskThreadService.getProcessCmd();
        // 正常跳转
        if (processCmd.isBack() == 0) {
            Map<String, Object> params = new HashMap<>(3);
            params.put("procInstId", processInstanceId);
            params.put("nodeId", nodeId);
            params.put("status", TaskOpinion.STATUS_AGREE);
            MultiInstanceLoopCharacteristics loopCharacteristics = ((Activity) execution.getCurrentFlowElement()).getLoopCharacteristics();
            if (loopCharacteristics != null) {
                int completeInstance=(Integer)execution.getVariable("nrOfCompletedInstances");
                int nrOfInstances=(Integer)execution.getVariable("nrOfInstances");
                if(completeInstance== nrOfInstances){
                    bpmProStatusDao.updStatus(params);
                }
            } else{
                bpmProStatusDao.updStatus(params);
            }
        }
        execution.removeVariable(varName);
    }

    @Override
    protected Integer getScriptType() {
        return BpmConst.END_SCRIPT;
    }
}
